<?php

namespace app\controllers;


use app\models\Area;
use app\tools\Re;
use Yii;

class AreaController extends BaseController
{
    //省份接口
    public function actionGetProvinceList(){
        $province_list = Area::find()->where(['parent_id' => 0])->andWhere("short_name not in ('香港', '澳门', '台湾')")->select("id,name")->all();
        return Re::data(['data' => $province_list]);
    }

    //根据省份获取城市
    public function actionGetCityListByProvince(){
        $id = Yii::$app->request->post('id', 0);
        if (empty($id)) {
          return Re::data(['data' => []]);
        }
        $city_list = [];
        $area_list = [];
        $city_list = Area::find()->where(['parent_id' => $id])->select("id,name")->all();
        $sh_city = $city_list[0];
        $area_list = Area::find()->where(['parent_id' => $sh_city->id])->andWhere("name <> '市辖区'")->select("id,name")->all();
        $data = [
           'city_list' => $city_list,
           'area_list' => $area_list,
        ];
        return Re::data(['data' => $data]);
    }

    //根据城市获取地区
    public function actionGetAreaListByCity(){
        $id = Yii::$app->request->post('id', 0);
        if (empty($id)) {
          return Re::data(['data' => []]);
        }
        $area_list = Area::find()->where(['parent_id' => $id])->andWhere("name <> '市辖区'")->select("id,name")->all();
        return Re::data(['data' => $area_list]);
    }

    //省市区一起返回
    public function actionList(){
        $p_list = Area::find()->where(['parent_id' => 0])->andWhere("short_name not in ('香港', '澳门', '台湾')")->select("area_code,name")->all();
        $province_list = [];
        if ($p_list) {
          foreach ($p_list as $k=>$v) {
            $index = $v->area_code/100000;
            $province_list[$index] = $v->name;
          }
        }
        $c_list = Area::find()->where(['level' => 1])->andWhere('area_code <> 0')->select("area_code,name")->all();
        $city_list = [];
        if ($c_list) {
          foreach ($c_list as $k1=>$v1) {
            $index1 = $v1->area_code/100000;
            $city_list[$index1] = $v1->name;
          }
        }
        $a_list = Area::find()->where(['level' => 2])->andWhere('area_code <> 0')->andWhere("name <> '市辖区'")->select("area_code,name")->all();
        $county_list = [];
        if ($a_list) {
          foreach ($a_list as $k2=>$v2) {
            $index2 = $v2->area_code/100000;
            $county_list[$index2] = $v2->name;
          }
        }
        $data = [
          'province_list' => $province_list,
          'city_list' => $city_list,
          'county_list' => $county_list,
        ];
        return Re::data(['data' => $data]);
    }
}
